import { defineBoot } from "#q-app/wrappers";
import common from "_s/common/localstore";
// import { asyncRouter, constantRouter } from "_s/router/routes";
import { userInfo } from "../config/user/index";
import { Notify } from "quasar";
import { useUserHook } from "_s/stores/modules/user";
const { setUserInfo } = useUserHook();

import { useMenuHook } from "_s/stores/modules/menu";
const { setRouter } = useMenuHook();
import type { RouteRecordNameGeneric, RouteRecordRaw } from "vue-router";

const homePage = "/";

// const setAccessMenu = (roleMenu: string[], asyncRouter: RouteRecordRaw[]): RouteRecordRaw[] => {
//   const res = [] as RouteRecordRaw[];
//   asyncRouter.forEach(item => {
//     const { meta, children } = item;
//     if (meta?.id && roleMenu.includes(meta.id)) {
//       if (children && children.length > 0) {
//         item.children = setAccessMenu(roleMenu, children);
//       }
//       res.push(item);
//     }
//   });
//   return res;
// };

const getMenuByRouter = (routers: RouteRecordRaw[], isAdmin: boolean, roleMenu: RouteRecordNameGeneric[]) => {
  const res = [] as RouteRecordRaw[];

  for (let i = 0; i < routers.length; i++) {
    const temp = routers[i] as RouteRecordRaw;
    const { meta, children, name } = temp;
    if (!name || meta?.hidden) continue;
    let childrenMenu = [] as RouteRecordRaw[];
    if (children && children.length > 0) {
      childrenMenu = getMenuByRouter(children, isAdmin, roleMenu);
    }
    if (isAdmin || roleMenu.includes(name)) {
      temp.children = childrenMenu;
      res.push(temp);
    }
  }

  return res;
};

export default defineBoot(({ app, router }) => {
  console.log(app);
  router.beforeEach(async (to, from, next) => {
    const token = common.getToken();

    if (!token && to.path != "/login") {
      return next({
        path: "/login"
      });
    }

    if (!token && to.path == "/login") {
      return next();
    }

    if (token && to.path == "/login") {
      return next({
        path: homePage
      });
    }
    if (to.path == "/limit") {
      return next();
    }

    try {
      // 权限判断
      const { code, data, msg } = await userInfo();

      if (code == -1 && !data) {
        // 用户在使用中被删除
        Notify.create({ type: "error", message: msg });
        return next({
          path: "/login"
        });
      }

      // 用户存在
      setUserInfo(data);
      const { auth } = data;
      const isAdmin = auth == 0;
      const roleMenu = ["user", "user_list", "test", "test_test1"] as RouteRecordNameGeneric[];
      const routers = router.options.routes;

      const routerConfig = getMenuByRouter([...routers], isAdmin, roleMenu);

      // const accessRoutes = !isAdmin ? asyncRouter : setAccessMenu(roleMenu, asyncRouter);
      // const menuRouter = constantRouter.concat(accessRoutes);
      setRouter(routerConfig); // 保存路由设置菜单

      // 管理员直接通过
      if (isAdmin) {
        return next();
      }

      // 用户没有权限
      if (roleMenu.length == 0) {
        Notify.create({ type: "error", message: "该用户没有权限，或者权限被删除" });
        // logout();
        common.setToken("");
        return next({
          path: "/login"
        });
      }

      // 有权限路由不存在
      const isHasRouter = router.hasRoute(to.name ? to.name : "");
      if (!isHasRouter) {
        return next({
          path: "/404"
        });
      }

      // 有权限，路由不匹配
      const isRoleMenu = roleMenu.includes(to.name);
      if (!isRoleMenu) {
        // 当前访问的路由不在权限列表中
        return next({
          path: "/limit"
        });
      }

      next();
    } catch {
      next({
        path: homePage
      }); // 这里相当于push到一个页面 不在进入路由拦截
    }

    // 用户权限处理
  });
});
